package com.maimao.info.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.maimao.core.constant.ListData;
import com.maimao.core.constant.RedisKeys;
import com.maimao.core.exception.MaiMaoDaoException;
import com.maimao.info.mapper.AddressMapper;
import com.maimao.info.mapper.RegionMapper;
import com.maimao.model.info.Address;
import com.maimao.model.info.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author MaoLin Wang
 * @date 2021/1/13 2:33 下午
 */
@Service
@Slf4j
public class AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private RegionService regionService;

    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public void add(Address address) {
        if (address.getIsDefault()) {
            addressMapper.updateNotDefault(address.getUserId());
        }
        addressMapper.insert(address);
    }

    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public void update(Address address) {
        if (address.getIsDefault()) {
            addressMapper.updateNotDefault(address.getUserId());
        }
        addressMapper.updateById(address);
    }

    public List<Address> userAddressList(Long userId) {
        if (userId == null) {
            return ListData.EMPTY_LIST;
        }
        List<Address> addressList = addressMapper.selectByUserId(userId);
        if (ObjectUtil.isNotEmpty(addressList)) {
            Optional<Address> defaultOp = addressList.stream().filter(address -> address.getIsDefault().equals(true)).findFirst();
            if (defaultOp.isPresent()) {
                addressList.remove(defaultOp.get());
                addressList.add(0, defaultOp.get());
            }

            List<Region> regionTree = regionService.regionTree();
            if (regionTree == null || regionTree.size() <= 0) {
                log.error("地区信息（空）获取异常....");
                return addressList;
            }
            Map<Integer, List<Region>> regionMap = regionTree.stream().collect(Collectors.groupingBy(Region::getId));

            for (Address address : addressList) {
                setAddressCityInfo(regionMap, address);
            }
        }
        return addressList;
    }

    private void setAddressCityInfo(Map<Integer, List<Region>> regionMap, Address address) {
        Integer provinceId = address.getProvinceId();
        List<Region> provinces = regionMap.get(provinceId);
        if (provinces != null && provinces.size() == 1) {
            address.setProvince(provinces.get(0).getName());
            List<Region> cityList = provinces.get(0).getChildren();
            Optional<Region> city = cityList.stream().filter(cityItem -> cityItem.getId().equals(address.getCityId())).findFirst();
            if (city.isPresent()) {
                address.setCity(city.get().getName());
                Optional<Region> areaOp = city.get().getChildren().stream().filter(areaItem -> areaItem.getId().equals(address.getAreaId())).findFirst();
                if (areaOp.isPresent()) {
                    address.setArea(areaOp.get().getName());
                }
            } else {
                address.setArea("错误地区");
                address.setCity("错误城市");
            }
        }
    }

    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public void setDefault(Long addressId, Long userId) {
        addressMapper.updateNotDefault(userId);
        addressMapper.updateDefault(addressId);
    }

    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public void delete(Long userId, Long id) {
        addressMapper.deleteById(id);
    }

    /**
     * 查询用户默认地址 没有默认地址就随机选择一个地址
     *
     * @param userId 用户id
     * @return 默认地址 or null
     */

    public Address selectDefault(Long userId) {
        Address defaultAddress = addressMapper.selectDefault(userId);
        if (defaultAddress == null) {
            List<Address> addresses = addressMapper.selectByUserId(userId);
            if (ObjectUtil.isEmpty(addresses)) {
                return null;
            }
            defaultAddress = RandomUtil.randomEle(addresses);
        }
        List<Region> regionTree = regionService.regionTree();
        if (regionTree == null || regionTree.size() <= 0) {
            log.error("地区信息（空）获取异常....");
            return null;
        }
        Map<Integer, List<Region>> regionMap = regionTree.stream().collect(Collectors.groupingBy(Region::getId));
        setAddressCityInfo(regionMap, defaultAddress);
        return defaultAddress;

    }
}
